package com.tensquare.spit.controller;

import com.tensquare.dto.PageResult;
import com.tensquare.dto.Result;
import com.tensquare.dto.StatusCode;
import com.tensquare.spit.pojo.Spit;
import com.tensquare.spit.service.SpitService;
import com.tensquare.util.JwtUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

@RestController
@CrossOrigin
@RequestMapping("/spit")
public class SpitController {

    @Autowired
    private SpitService spitService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private HttpServletRequest request;

    //吐槽点赞
    @PutMapping("/thumbup/{id}")
    public Result thumbup(@PathVariable String id){

        //获取token
        String auth = request.getHeader("Authorization");
        System.out.println("auth:"+auth);

        //解析token
        Claims parseJWT = null;
        if(auth.startsWith("Bearer ")) {
            try {
                parseJWT = jwtUtil.parseJWT(auth.substring(7));
            } catch (ExpiredJwtException e) {
                System.out.println("token过期了："+e.getMessage());
                return new Result(false,StatusCode.ACCESS_ERROR,"token已过期，请重新登录！");
            } catch (Exception e) {
                System.out.println("解析jwt异常："+e.getMessage());
                return new Result(false,StatusCode.ACCESS_ERROR,"非法token，请不要搞我！");
            }
        }
        //查看用户是否是管理员
        if(parseJWT==null || !"user".equals(parseJWT.get("roles"))) {
            return new Result(false,StatusCode.ACCESS_ERROR,"请先登录");
        }

        //模拟用户的id
        String userid = parseJWT.getId();

        //key
        String key = "thumbup_"+userid+"_"+id;
        //从缓存中查询
        String flag = (String)redisTemplate.opsForValue().get(key);

        //判断重复点赞
        if(StringUtils.isNotBlank(flag)){
            return new Result(false, StatusCode.REPEATE_ERROR, "亲，您已经点过赞啦！");
        }

        //可以点赞
        spitService.thumbup(id);
        //把标记放入缓存
        redisTemplate.opsForValue().set(key,"1",5, TimeUnit.DAYS);
        return new Result(true, StatusCode.OK, "恭喜：点赞成功啦~");
    }

    //查询评论
    @GetMapping("/comment/{parentid}/{page}/{size}")
    public Result comment(@PathVariable String parentid,
                          @PathVariable int page,
                          @PathVariable int size
                          ){
        //查询评论的数据
        Page<Spit> pageBean = spitService.comment(parentid,page,size);
        return new Result(true, StatusCode.OK, "查询吐槽评论成功",
                new PageResult<Spit>(pageBean.getTotalElements(),pageBean.getContent())
                );
    }

    //查询所有
    @GetMapping
    public Result findAll(){
        return new Result(true, StatusCode.OK, "查询所有吐槽数据成功", spitService.findAll());
    }

    //查询一个
    @GetMapping("/{id}")
    public Result findById(@PathVariable String id){
        return new Result(true, StatusCode.OK, "查询一个吐槽数据成功", spitService.findById(id));
    }

    //新增
    @PostMapping
    public Result add(@RequestBody Spit spit){
        spitService.add(spit);
        return new Result(true, StatusCode.OK, "新增一个吐槽数据成功");
    }

    //修改
    @PutMapping("/{id}")
    public Result update(@PathVariable String id,@RequestBody Spit spit){
        spit.setId(id);
        spitService.update(spit);
        return new Result(true, StatusCode.OK, "修改一个吐槽数据成功");
    }

    //修改
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable String id){
        spitService.deleteById(id);
        return new Result(true, StatusCode.OK, "删除一个吐槽数据成功");
    }
}
